package com.telrob.tool;

import android.content.Context;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class JsUdp {
    private static final String TAG="zhang2";
    private Context context;
    public JsUdp(Context context) {
        this.context = context;
    }
    @JavascriptInterface
    public JsUdpClient clientUdp(){
        JsUdpClient jsudp= new JsUdpClient();
        return jsudp;
    }

    @JavascriptInterface
    public void test(ValueCallback<String> callback){
        System.out.println("zhang2--------------------");
        System.out.println("zhang2- "+callback);
    }

    @JavascriptInterface
    public String getVersion(){
        return "1.0.0";
    }

    // udp 客户端
    public  class JsUdpClient{
        private DatagramSocket clientSocket=null;
        public JsUdpClient(){
            try{
                this.clientSocket=new DatagramSocket();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        @JavascriptInterface
        public boolean sendTo(String ip,int port,byte[] data){
            DatagramPacket pack=new DatagramPacket(data,0,data.length,new InetSocketAddress(ip,port));
            if(clientSocket!=null){
                try{
                    clientSocket.send(pack);
                    return true;
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
            return false;
        }

        @JavascriptInterface
        public boolean close(){
            if(clientSocket!=null){
                clientSocket.close();
            }
            return true;
        }
        @JavascriptInterface
        public String getVersion(){
            return "udp clinet 1.0.0";
        }

    }




}
